package webmarket;

/**
 * @author Simos
 */

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import model.Store;
import model.StoreProduct;

public class AdminStore extends javax.swing.JFrame {

    private static EntityManager em;
    
    /**
     * Creates new form AdminStore
     */
    
    public AdminStore() {
         EntityManagerFactory emf = Persistence.createEntityManagerFactory("WebMarketPU");
        // Δημιουργία του Entity Manager
        em = emf.createEntityManager();
        initComponents();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        WebMarketPUEntityManager0 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("WebMarketPU").createEntityManager();
        storeQuery = java.beans.Beans.isDesignTime() ? null : WebMarketPUEntityManager0.createQuery("SELECT s FROM Store s ");
        storeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(storeQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        newStoreButton = new javax.swing.JButton();
        editStoreButton = new javax.swing.JButton();
        delStoreButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("WebMarket - Διαχείριση καταστημάτων (administrator)");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Διεύθυνση");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(45);
        }

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Λίστα καταστημάτων");

        newStoreButton.setText("Νέο");
        newStoreButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newStoreButtonActionPerformed(evt);
            }
        });

        editStoreButton.setText("Τροποποίηση");
        editStoreButton.setEnabled(false);
        editStoreButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editStoreButtonActionPerformed(evt);
            }
        });

        delStoreButton.setText("Διαγραφή");
        delStoreButton.setEnabled(false);
        delStoreButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delStoreButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Πίσω");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(294, 294, 294)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 632, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newStoreButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(67, 67, 67)
                                .addComponent(editStoreButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(delStoreButton)
                                .addGap(67, 67, 67)
                                .addComponent(exitButton)))))
                .addContainerGap(73, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {delStoreButton, editStoreButton, exitButton, newStoreButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newStoreButton)
                    .addComponent(editStoreButton)
                    .addComponent(delStoreButton)
                    .addComponent(exitButton))
                .addGap(47, 47, 47))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        AdminFrame mainadmin = new AdminFrame();
        mainadmin.setLocationRelativeTo(null);
        mainadmin.setVisible(true);
        dispose();
    }//GEN-LAST:event_exitButtonActionPerformed

    private void delStoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delStoreButtonActionPerformed
        // Διαγραφή καταστήματος.
        int selected = jTable1.getSelectedRow();
        int n;
        Store delStore = storeList.get(selected);
        // Ελέγχουμε αν υπάρχουν παραγγελίες για αυτό το κατάστημα.
        if (delStore.getPurchaseList().size() > 0) {
            n = JOptionPane.showOptionDialog(rootPane,
                "Το κατάστημα δε μπορεί να διαγραφεί γιατί\n" +
                "υπάρχουν παραγγελίες σχετικές με αυτό.\n" +
                "Θέλετε να διαγραφούν τα προϊόντα από το\n" +
                "κατάστημα και να αλλάξει η διεύθυνσή του\n" +
                "σε:   «Το κατάστημα έχει κλείσει !» ;"
                , "    Προσοχή !!!", 2, 2, null, null, rootPane);
        }
        else {
            n = JOptionPane.showOptionDialog(rootPane,
                "Το κατάστημα και τα προϊόντα που\n" +
                "υπάρχουν σε αυτό θα διαγραφούν !\n" +
                "       Είστε σίγουροι;"
                , "    Προσοχή !!!", 2, 2, null, null, rootPane);
        }
        // Εαν επιλέξουμε τη διαγραφή του καταστήματος
        if (n == 0) {
            em.getTransaction().begin();
            // Αν υπάρχουν παραγγελίες δε το σβήνουμε.
            if (delStore.getPurchaseList().size() >0) {
                delStore.setAddress("Το κατάστημα έχει κλείσει !");
                Store temp = em.merge(delStore);
                em.persist(temp);
                em.getTransaction().commit();
                // Πρέπει όμως να σβήσουμε τα συσχετισμένα προϊόντα.
                if (delStore.getStoreProductList().size() >0) {
                    StoreProduct tempsp;
                    em.getTransaction().begin();
                    for (StoreProduct sp : delStore.getStoreProductList()) {
                        tempsp = em.merge(sp);
                        em.remove(tempsp);
                    }
                    em.getTransaction().commit();
                }
            }
            // Καταστήματα χωρίς παραγγελίες απλά τα σβήνουμε.
            else {
                Store temp = em.merge(delStore);
                em.remove(temp);
                em.getTransaction().commit();
                storeList.remove(selected);
            }
        }
        AdminStore adminstore = new AdminStore();
        adminstore.setLocationRelativeTo(null);
        adminstore.setVisible(true);
        dispose();
    }//GEN-LAST:event_delStoreButtonActionPerformed

    private void editStoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editStoreButtonActionPerformed
        // Τροποποίηση καταστήματος
        int selected = jTable1.getSelectedRow();
        // Καλούμε το AdminEditStore σε mode 2 (τροποποίηση)
        AdminEditStore editStore = new AdminEditStore(storeList.get(selected),2);
        editStore.setLocationRelativeTo(null);
        editStore.setVisible(true);
        dispose();
    }//GEN-LAST:event_editStoreButtonActionPerformed

    private void newStoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newStoreButtonActionPerformed
        // Δημιουργία καταστήματος
        Store selectedStore = new Store();
        // Καλούμε το AdminEditStore σε mode 1 (δημιουργία)
        AdminEditStore editStore = new AdminEditStore(selectedStore,1);
        editStore.setLocationRelativeTo(null);
        editStore.setVisible(true);
        dispose();
    }//GEN-LAST:event_newStoreButtonActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (jTable1.getSelectedRow() >= 0) {
            editStoreButton.setEnabled(true);
            delStoreButton.setEnabled(true);
        }
    }//GEN-LAST:event_jTable1MouseClicked
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminStore.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminStore.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminStore.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminStore.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AdminStore().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager WebMarketPUEntityManager0;
    private javax.swing.JButton delStoreButton;
    private javax.swing.JButton editStoreButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton newStoreButton;
    private java.util.List<model.Store> storeList;
    private javax.persistence.Query storeQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}